package com.xiamao.jdt.service;

import com.xiamao.jdt.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ChargingDeviceService {
    /**
     * 处理并排序设备充电信息
     *
     * @param deviceInfo           设备信息
     * @param chargeInfo           充电信息
     * @param maxChargePercentages 最大充电百分比设置
     * @return 排序后的设备充电信息列表
     */
    public List<ChargingDeviceInfo> processAndSortChargingDeviceInfo(final String isShowAll,
                                                                     final DeviceInfo deviceInfo,
                                                                     final ChargeInfo chargeInfo,
                                                                     final Map<String, Integer> maxChargePercentages) {
        // 检查必要数据是否存在
        if (deviceInfo == null || chargeInfo == null) {
            return new ArrayList<>();
        }
        final List<ChargingDeviceInfo> result = new ArrayList<>();
        // 获取SOC信息
        final List<SocInfo> socInfos = chargeInfo.getSocInfos();
        final Map<String, SocInfo> socInfoMap = Optional.ofNullable(socInfos).orElse(new ArrayList<>()).stream()
                .collect(Collectors.toMap(SocInfo::key, Function.identity(), (k1, k2) -> k1));

        // 获取设备信息
        final List<Device> devices = deviceInfo.getInfos();
        if (CollectionUtils.isEmpty(devices)) {
            return new ArrayList<>();
        }
        for (final Device device : devices) {
            final List<InterfaceInfo> interfaceInfos = device.getInterfaceInfos();
            if (CollectionUtils.isEmpty(interfaceInfos)) {
                continue;
            }
            for (final InterfaceInfo interfaceInfo : interfaceInfos) {
                final String key = interfaceInfo.getDeviceId() + ":" + interfaceInfo.getInterfaceId();
                final ChargingDeviceInfo chargingDeviceInfo = new ChargingDeviceInfo();
                chargingDeviceInfo.setDeviceId(device.getDeviceId());
                chargingDeviceInfo.setDeviceNo(device.getDeviceNo());
                chargingDeviceInfo.setDeviceName(device.getDeviceName() + "-" + interfaceInfo.getName());
                // 获取设备名称的编码
                final String deviceName = Optional.of(device).map(Device::getDeviceName).orElse("-");
                chargingDeviceInfo.setDeviceNameSort(Integer.valueOf(deviceName
                        .replace("#", "")
                        .replace("-", "")));
                chargingDeviceInfo.setInterfaceId(interfaceInfo.getInterfaceId());
                chargingDeviceInfo.setStateStr(interfaceInfo.getStateStr());
                //初始货
                chargingDeviceInfo.setIsSocietyCar(1);
                chargingDeviceInfo.setTargetRate(new BigDecimal(-1));
                chargingDeviceInfo.setMaxChargePercent(100); // 默认100%
                chargingDeviceInfo.setHasMaxChargePercentSet(false);
                chargingDeviceInfo.setTargetRate(new BigDecimal(-1));
                final SocInfo socInfo = socInfoMap.getOrDefault(key, new SocInfo());
                if (StringUtils.equals(isShowAll, "N") && StringUtils.isBlank(socInfo.getCarNo())) {
                    continue;
                }
                chargingDeviceInfo.setActualSoc(socInfo.getSoc());
                if (interfaceInfo.getState() != 3) {
                    result.add(chargingDeviceInfo);
                    continue;
                }
                if (StringUtils.isNotBlank(socInfo.getCarTypeName())) {
                    chargingDeviceInfo.setIsSocietyCar(0);
                }
                chargingDeviceInfo.setCarNo(socInfo.getCarNo());
                chargingDeviceInfo.setCarTypeName(socInfo.getCarTypeName());
                // 获取设置的最大充电百分比
                final Integer maxPercent = maxChargePercentages.get(key);
                if (maxPercent != null) {
                    chargingDeviceInfo.setMaxChargePercent(maxPercent);
                    chargingDeviceInfo.setHasMaxChargePercentSet(true);
                    final BigDecimal targetRate = new BigDecimal(socInfo.getSoc())
                            .divide(new BigDecimal(maxPercent), 2, RoundingMode.HALF_UP)
                            .multiply(new BigDecimal(100));
                    chargingDeviceInfo.setTargetRate(targetRate);
                    chargingDeviceInfo.setSocDifference(socInfo.getSoc() - maxPercent);
                } else {
                    chargingDeviceInfo.setSocDifference(Optional.of(socInfo.getSoc()).orElse(0) - 100);
                }
                result.add(chargingDeviceInfo);
            }
        }
        final Comparator<ChargingDeviceInfo> comparator = Comparator.comparing(ChargingDeviceInfo::getTargetRate).reversed()
                .thenComparing(ChargingDeviceInfo::getIsSocietyCar)
                .thenComparing(ChargingDeviceInfo::getDeviceNameSort);
        result.sort(comparator);
        return result;
    }
}